class CommunitiesController < ApplicationController
    include AuthenticatedSystemBrowse
  
    before_filter :login_required, :only => [ :live, :edit, :update, :add_site, :set_neighbor ]
  
    def index
        if current_user.nil? || current_user.community.nil?
            redirect_to(:controller => 'browse', :action => 'comm_list' )
        else
            redirect_to community_url(current_user.community.district, current_user.community )
        end	
    end

    def live
        community = Community.find(:first, :conditions => [ "id = ?",params[:id]])
        current_user.setpos(community)
        redirect_to community_url(community.district, community )
    end
    
    def life
        #        community = Community.find(:first, :conditions => [ "id = ?",params[:id]])
        #        current_user.setpos(community)
        #        redirect_to community_url(community.district, community )
        @districts = District.find(:all)
        @district = @districts[0]
        @communities = Community.paginate_by_district_id @district, :page => 1
    end

    def cats
        @community = Community.find(params[:id])
        @cat = PostCategory.find(params[:cat])
        @site_categories = SiteCategory.find(:all)
        @new_users = User.find(:all, :conditions => ["community_id = ?", @community.id], :order => "users.join_community_at desc")
        @posts = CommonPost.paginate_by_community_id_and_post_category_id @community, @cat, :include => [:user, :post_category, {:community => :district} ], :page => params[:page], :order => "replied_at DESC"
        @page_title = @community.district.title + ' - '+ @community.title + ' - ' + @cat.title
    end
  
    def search
        if params[:q].nil? || params[:q].blank?
            redirect_to_referer(:controller => 'communities', :action => 'index')
        elsif params[:commit].nil? || params[:commit] == '搜索社区' || params[:commit] == '搜索'
            @communities = Community.paginate_search(params[:q], {:page => params[:page]})
            @hot_communities = Community.find(:all, :conditions => @find_sql, :order => 'common_posts_count desc limit 10')
            @page_title = '搜索 - ' + params[:q]
        elsif params[:commit] == '搜索场所'
            redirect_to(:controller => 'sites', :action => 'search', :id => params[:id] , :q => params[:q] )
        else
            redirect_to_referer(:controller => 'communities', :action => 'index')
	end
    end
  
    def search_users
        if params[:id].nil?
            redirect_back_or_default(:controller => 'communities', :action => 'index')
        else
            @community = Community.find(:first, :conditions => ["id = ?", params[:id]])
            if @community.nil?
                redirect_back_or_default(:controller => 'communities', :action => 'index')
            else
                if params[:q].nil? || params[:q].blank?
                    redirect_back_or_default community_url(@community.district, @community)
                else
                    @users = User.paginate_search(params[:q], {:page => params[:page]}, {:conditions => ["community_id = ?", params[:id]]})
                end
            end
        end
    end
  
    def add_site
        @site = Site.new(params[:site])
        @community = Community.find(:first, :conditions => [ "id = ?", params[:id]])
        @page_title = @community.district.title + ' - ' + @community.title + ' - 添加场所'
        @site_categories = SiteCategory.find(:all).map{|u| [u.title, u.id]}
        return unless request.post?
        Site.transaction do
            #@site.created_user_id = current_user.id
            @site.save!
            current_user.sites << @site
            community_site = CommunitySite.new(:community => @community, :site => @site)
            community_site.save!
            current_user.add_scores(5)
        end
        redirect_back_or_default site_url(@site )
        rescue ActiveRecord::RecordInvalid
        render :action => 'add_site', :id => @community
    end
  
    def show
        @community = Community.find(params[:id])
        @district = @community.district
        
	@new_users = User.find(:all, :conditions => ["community_id = ?", @community.id], :order => "users.join_community_at desc")
	@page_title = @community.district.title + ' - '+ @community.title
	respond_to do |format|
            format.html do
                @tags = community_tags(@community)
                @like_groups = get_users_like_groups(@community.users)
                @posts = CommonPost.paginate_by_community_id @community, :include => [:user, :post_category, {:community => :district} ], :page => params[:page], :order => "replied_at DESC"
            end
            format.rss  do
                @posts = CommonPost.find_all_by_community_id @community.id, :include => [:user, :post_category, {:community => :district} ], :order => "replied_at DESC", :limit => 25
                #render :xml => @posts.to_xml
                render :action => "show.rxml", :layout => false
            end
        end
    end
    
    def sites
        @community = Community.find(params[:id], :include => [ :sites, :district ])
        @sites = @community.sites
        @page_title = @community.district.title + ' - '+ @community.title + ' - 周边场所'
	respond_to do |format|
            format.html do
                @tags = community_tags(@community)
                sites_ids = @sites.collect{|n| n.id}.join(',')
                sites_ids = [0] if sites_ids.size < 1
                @district = @community.district
                @posts = SitePost.paginate :conditions => ["posts.site_id in (#{sites_ids})"], :include => [:user, :site ], :page => params[:page], :order => "replied_at DESC"
            end
            format.rss  do
                sites_ids = @sites.collect{|n| n.id}.join(',')
                sites_ids = [0] if sites_ids.size < 1
                @posts = SitePost.find :all, :conditions => ["posts.site_id in (#{sites_ids})"], :include => [:user, :site ], :order => "replied_at DESC", :limit => 25 
                #render :xml => @posts.to_xml
                render :action => "sites.rxml", :layout => false
            end
        end
    end
    
    def forums
        @community = Community.find(params[:id], :include => [ :sites, :district, {:community_forum => :topics} ])
        @forum = @community.community_forum
        @page_title = @community.district.title + ' - '+ @community.title + ' - 论坛'
	respond_to do |format|
            format.html do
                @tags = community_tags(@community)
                @topics = @community.community_forum.topics.paginate :include => [ :user, :forum ], :order => "replied_at DESC", :page => params[:page]
            end
            format.xml  do
                @topics = @community.community_forum.topics.find(:all, :include => [ :user, :forum ], :order => "replied_at DESC limit 6")
                render :xml => @topics.to_xml
            end
        end
    end
    
    def edit
        @community = Community.find(:first, :conditions => [ "id = ?", params[:id]])
        if !@community.can_edit?(current_user)
            raise ActiveRecord::RecordNotFound
        else
            @page_title = '编辑' + @community.title + '社区资料'
        end
    end
    
    def update
        @community = Community.find(:first, :conditions => [ "id = ?", params[:id]])
   	@community.update_attributes(params[:community])
        current_user.add_scores(3)
        respond_to do |format|
            format.html { redirect_to community_url(@community.district, @community) }
            format.xml  { head 200 }
        end
    end
    
    def users
        @community = Community.find(:first, :conditions => [ "id = ?", params[:id]])
        #@users = @community.users
        @users = User.paginate_by_community_id @community, :page => params[:page]
        @page_title = @community.district.title + ' - '+ @community.title + ' - 成员'
        respond_to do |format|
            format.html { render :action => "users.rhtml" }
            format.xml  { render :xml => @users.to_xml }
        end
    end
  
    def set_neighbor
        return unless request.post?
        @community = Community.find(:first, :conditions => [ "id = ?", params[:id]])
        if !@community.nil? && @community != current_user.community
            comm = current_user.community.neighbors.find(:first, :conditions => ["neighbor_id = ?", @community.id], :select => "communities.*, community_neighbors.click_counts as click_counts")
            if comm.nil? && @community != current_user.community
                community_neighbor = CommunityNeighbor.new(:community => current_user.community, :neighbor => @community)
                community_neighbor.save!
            else
                click_counts = comm.click_counts.to_i
                #事务处理
                Community.transaction do
                    community_neighbor = CommunityNeighbor.find(:first, :conditions => [ "community_id = ? and neighbor_id = ?", current_user.community, @community])
                    community_neighbor.click_counts = click_counts + 1
                    community_neighbor.save!
                end
            end
            #set session
            if session[:community_set_neighbor].nil?
                session[:community_set_neighbor] = Array.new
            end
                session[:community_set_neighbor].push(@community.id)
        end
        current_user.add_scores(2)
        render :text => "谢谢参与"
    end
  
    def ajaxsearch
        if !params[:search].nil? && !params[:search].blank?
            @communities = Community.find_by_contents(params[:search], {:limit => 10})
        end
        render :partial=>'ajaxsearchResults'
    end
end
